const tf = require('@tensorflow/tfjs-core')
const posenet = require('@tensorflow-models/posenet')
import Notify from '../../notify/notify';
const app = getApp()

Page({
  data: {
    animationMain: null, //正面
    animationBack: null, //背面,
    videoClass: "",
    cameraClass: "camera-hidden",
    isTaiQian: true,
    jindu: 0,
    time: NaN,
    switchData: "开",
    taiqian: "台前",
    gradientColor: {
      '0%': '#C8DEFF',
      '100%': '#6495ED',
    },
    mySrc: ""
  },
  //async后不能有function
  onLoad(options) {

    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: (res) => {
              app.globalData.avatarUrl = res.userInfo.avatarUrl,
                app.globalData.userInfo = res.userInfo
            }
          })
        }
      }
    })
    this.videoSrcIdx = options
    // console.log("options", typeof Number(options.myVideoIdx))
    // console.log("options", options.myVideoIdx))


    let src = ''

    switch (Number(options.myVideoIdx)) {
      case 0:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc01.mp4?sign=a47017e832d9572554153fc41566e44e&t=1592150974";
        break;
      case 1:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc01.mp4?sign=a47017e832d9572554153fc41566e44e&t=1592150974";
        break;
      case 2:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc02.mp4?sign=4f0bdc28db439d44f76de67e9e630520&t=1592151003";
        break;
      case 3:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc03.mp4?sign=c3e67ae1920a19b3681b9ad49bd734cb&t=1592151014";

        break;
      case 4:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc04.mp4?sign=d39179376f092f7257d1c6e7c74d609a&t=1592151025";

        break;
      case 5:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc05.mp4?sign=9341b9d3c79ce75c345ff1c906ca13c8&t=1592151036";

        break;
      case 6:
        src = "https://7265-release-mm1hb-1301926727.tcb.qcloud.la/jimu/ybjc06.mp4?sign=ea5bb4bca663496f3ebc1b4657b6f6e4&t=1592151046";
        break;
      default:
        break
    }
    this.setData({
      mySrc: src
    })
    // console.log("mySrc", this.data.mySrc)

    // if (app.globalData.isNewUser) {
    //   // console.log("isNewUser",app.globalData.isNewUser)
    //   this.setData({
    //     show: true
    //   })
    // }
  },
  async onReady() {
    this.isProcessing = false
    this.loadPosenet()
    this.videoContext = wx.createVideoContext('ybjcVideo')

    const camera = wx.createCameraContext(this)

    let count = 0
    this.listener = camera.onCameraFrame((frame) => {
      if (this.data.jindu >= 100) {
        // console.log("jindu:",this.data.jindu )
        this.listener.stop()

        if (this.data.switchData == "关" || !isNaN(this.data.time)) {
          // console.log("off")
          this.setData({
            switchData: "开",
            time: NaN
          })
          // console.log("======")
          if (!isNaN(this.data.time)) {
            //ToDo: 这没走，上边一直走
            clearInterval(this.data.time)
            console.log("clear")
          }
          // console.log("---",app.globalData.isNewUser)
          if (app.globalData.isNewUser) {
            this.myDataAdd()
            app.globalData.isNewUser = false
            // console.log("myDataAdd")
            // console.log("xin",app.globalData.isNewUser)
          } else {
            this.myDataUpdate()
            // console.log("myDataUpdate")
          }
        }

        if (this.isProcessing) {

          Notify({
            message: '打卡成功',
            color: '#333',
            background: '#C7EDCC'
          });
        }
        // console.log("---",this.data.time)

        // if (!isNaN(this.data.time)) {
        //   //ToDo: 这没走，上边一直走
        //   clearInterval(this.data.time)
        //   // console.log("clear")
        // }
        this.isProcessing = false
      }
      count++
      if (count >= 4) {
        if (this.net && this.isProcessing) {
          this.analyzeData(frame)
        }
        count = 0
      }
    })
    Notify({
      message: '点[开]\n开始做操',
      color: '#333',
      background: '#C7EDCC'
    });


    // this.onGetOpenid()

  },
  onUnload: function () {
    this.myDataQuery()
    console.log("---")
  },
  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'mylogin',
      data: {},
      success: res => {
        // console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        this.myOpenid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  myDataAdd: function () {
    const db = wx.cloud.database()

    let useropenid = app.globalData.openid
    let myDate = new Date()
    // console.log(myDate)
    let ybjcIdx = this.videoSrcIdx

    // let myMonth = myDate.getMonth + 1
    // let myDay = myDate.getDate()

    // console.log(myMonth, ybjcIdx)

    db.collection('ybjc').add({
      data: {
        useropenid: useropenid,
        userdates: [myDate]
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        // this.setData({
        //   counterId: res._id,
        //   count: 1
        // })
        // console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  myDataUpdate() {
    const db = wx.cloud.database()
    const _ = db.command

    let user_id = app.globalData.user_id

    let mydate = new Date()

    // console.log(user_id,app.globalData.user_id)

    db.collection('ybjc').doc(user_id).update({
      data: {
        userdates: _.push([mydate])
      },
      success: res => {
        // console.log('[数据库] [更新记录] ', res)
      },
      fail: err => {
        console.error('[数据库] [更新记录] 失败：', err)
      }
    })
  },
  myDataQuery: function () {
    const db = wx.cloud.database()
    let useropenid = app.globalData.openid

    // 查询当前用户所有的 counters
    db.collection('ybjc').where({
      useropenid: useropenid
      // _id:"e984b69a5ee6f12c001912e452e8d776"
    }).get({
      success: res => {

        // let userData=JSON.stringify(res.data, null, 2)//？？？
        //!!!
        let userDatas = res.data
        // console.log(userDatas)

        if (userDatas.length > 0) {
          app.globalData.isNewUser = false
          app.globalData.user_id = userDatas[0]._id
          app.globalData.userdates = userDatas[0].userdates
          // console.log(app)

        } else {
          // app.globalData.isNewUser = true
        }
        // console.log("===", app)
      },
      fail: err => {
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },
  onSwitch() {
    // console.log("---",app.globalData)
    if (!app.globalData.openid) {
      this.onGetOpenid()
      // console.log("getopenid")
    }
    // console.log("onSwitch")
    if (this.net) {
      if (!this.isProcessing) {
        this.listener.start()
        this.videoContext.play()
        this.setData({
          switchData: "关"
        })
        this.isProcessing = true
      } else {
        this.listener.stop()
        this.videoContext.pause()
        this.setData({
          switchData: "开"
        })
        this.isProcessing = false
        if (!isNaN(this.data.time)) {
          clearInterval(this.data.time)
          this.setData({
            time: NaN
          })
        }
      }
    } else {
      Notify({
        message: '模型加载中...',
        color: '#333',
        background: '#C8DEFF'
      });
    }
  },
  async loadPosenet() {
    this.net = await posenet.load({
      architecture: 'MobileNetV1',
      outputStride: 16,
      inputResolution: 193,
      multiplier: 0.5,
      modelUrl: 'https://www.gstaticcnapps.cn/tfjs-models/savedmodel/posenet/mobilenet/float/050/model-stride16.json'
    })
    console.log(this.net)
  },
  //检测姿态
  async detectPose(frame, net) {
    //图像数据
    // console.log(frame)

    const imgData = {
      data: new Uint8Array(frame.data),
      width: frame.width,
      height: frame.height
    }
    //tidy方法来提升性能，回收不用变量
    const imgSlice = tf.tidy(() => {
      //将图片转为张量，4通道
      const imgTensor = tf.browser.fromPixels(imgData, 4)
      //长-到最后，宽-到最后，4通道-去掉α通道，留3个通道
      return imgTensor.slice([0, 0, 0], [-1, -1, 3])
    })
    // console.log(imgSlice)

    const pose = await net.estimateSinglePose(imgSlice, {
      flipHorizontal: false
    })
    imgSlice.dispose()
    // console.log("pose",pose)
    return pose
  },
  async analyzeData(frame) {
    const pose = await this.detectPose(frame, this.net)
    // console.log("pose", pose)
    // if (pose == null || this.canvas == null) return
    if (pose == null) return

    if (pose.score >= 0.33) {
      let myPoints = pose.keypoints

      let leftWrist = myPoints[9].position.y
      let rightWrist = myPoints[10].position.y


      let leftWristScore = myPoints[9].score
      let rightWristScore = myPoints[10].score

      let leftShoulder = myPoints[5].position.y
      let rightShoulder = myPoints[6].position.y

      let isOK = (leftShoulder - leftWrist) > 0 && leftWristScore > 0.3 || (rightShoulder - rightWrist) > 0 && rightWristScore > 0.3

      // console.log(leftShoulder,leftWrist)
      if (isOK) {
        // console.log("do")
        if (isNaN(this.data.time)) {
          // console.log("ing...")
          var time = setInterval(() => {
            // console.log(time)
            this.setData({
              jindu: this.data.jindu + 4
            })
            // console.log(this.data.jindu)

          }, 1000)
          // console.log("---", time)
          this.setData({
            time: time
          })
          // console.log("data1:",this.data.time)
        }
      } else {
        if (!isNaN(this.data.time)) {
          // console.log("no")
          clearInterval(this.data.time)
          this.setData({
            time: NaN
          })
          // console.log("data2:",this.data.time)
        }
      }
    } else {
      Notify({
        type: 'warning',
        message: '请转到[幕后]\n并调整姿势'
      });
    }
  },
  calculateLen(position1, position2) {
    if (!position1 || !position2) return

    let x1 = position1.x
    let y1 = position1.y
    let x2 = position2.x
    let y2 = position2.y

    let len = Math.round(Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)))

  },
  rotateFn(e) {

    let isTaiQian = this.data.isTaiQian

    this.animation_main = wx.createAnimation({
      timingFunction: 'linear'
    })
    this.animation_back = wx.createAnimation({
      timingFunction: 'linear'
    })
    // 点击正面

    if (isTaiQian) {
      this.animation_main.rotateY(180).step()
      this.animation_back.rotateY(0).step()
      this.setData({
        videoClass: "video-hidden",
        cameraClass: "",
        animationMain: this.animation_main.export(),
        animationBack: this.animation_back.export(),
        isTaiQian: false,
        taiqian: "幕后"
      })
    } else {
      // this.data.isHiddenVideo="display:none"
      this.animation_main.rotateY(0).step()
      this.animation_back.rotateY(-180).step()
      this.setData({
        videoClass: "",
        cameraClass: "camera-hidden",
        animationMain: this.animation_main.export(),
        animationBack: this.animation_back.export(),
        isTaiQian: true,
        taiqian: "台前"
      })
    }
  },
})